package BusinessLogic;

import Presentation.frmClient;
import java.io.*;
import java.net.Socket;
import java.nio.charset.Charset;

public class ClientServices implements Cloneable, Runnable{
    
    private Socket cs=null;
    private boolean Stop=false;
    private BufferedWriter bw=null;
    private BufferedReader br=null;
    public boolean Connected=false;
    private Thread Runner=null;
 //   static frmClient;
    //Tao socket
    public ClientServices(String host,int port)
    {
        try
        {
            cs=new Socket(host,port);
            Runner=new Thread(this);
            br=new BufferedReader(new InputStreamReader(cs.getInputStream(),Charset.forName("UTF-8").newDecoder()));
            bw=new BufferedWriter(new OutputStreamWriter(cs.getOutputStream(),Charset.forName("UTF-8").newEncoder()));
            Runner.start();
            Connected=true;
        }
        catch(Exception e)
        {
            startError(false);
        }
    }
    
    //Chay client
    public void run()
    {
        if(cs!=null) 
        {
            while(!Stop)
            {
                try{
                   String str=br.readLine();
                   frmClient.processing(str);
                }
                catch(Exception e){
                  Stop=true;
                }
            }
            if(Stop==true){
                try {
                    stop();
                } catch (IOException ex) {
                }
                
            }
        }
    }
    
    //Tắt socket
    public void stop() throws IOException
    {
        bw.close();
        br.close();
        cs.close();    
    }
    
    public synchronized boolean sendData(String str)
    {
        if(cs!=null)
        {
            try{
                bw.write(str);
                bw.newLine();
                bw.flush();
                return true;
            }
            catch(Exception e){
                return false;
            }
        }
        else return false;
    }
    
    public static boolean startError(boolean b){
        return b;
    }
    
}
